﻿using System;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Globalization;
//using Office = Microsoft.Office.Core;

/* INSTRUCTIONS

* ------------------- for Dev machines ------------------------: 
* BUILD & SETUP (for UPGRADE the same):
* Close Outlook
* Compile - this is enough to get it listed in Outlook Addins
* Open Outlook

UNINSTALL (not needed for UPGRADE):
* Close Outlook
* remove from registry:    HKEY_CURRENT_USER\Software\Microsoft\Office\Outlook\AddIns\Mail2Portfolio
* Open Outlook

------------------- for non-Dev (end user) machines ----------: 
* BUILD:
* Compile
* Publish (a command in projects context menu)
* take files from   ...\publish\*.*    to end user machine

SETUP (for UPGRADE the same):
* Close Outlook
* Double click ...\publish\Mail2Portfolio.vsto   and continue with defaults ("Install" button etc)
* Open Outlook

UNINSTALL (not needed for UPGRADE):
* Close Outlook
* Uninstall from Control Panel ("Mail2Portfolio")
* run command:    rundll32 dfshim CleanOnlineAppCache
* not sure if this last one is really necessary, but just in case. Info from http://stackoverflow.com/questions/7915257/uninstall-vsto-plugin
*/

namespace Mail2Portfolio
{
    public partial class ThisAddIn
    {
        MainForm mainForm;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            this.Application.NewMailEx += new Outlook.ApplicationEvents_11_NewMailExEventHandler(olApp_NewMail);
            
            mainForm = new MainForm();
            mainForm.Show();
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            mainForm.Close();
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion

        private string getPRSearchKey(Outlook.MailItem m)
        {
            return m.PropertyAccessor.BinaryToString(m.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x300B0102"));
        }

        private void olApp_NewMail(string entryIDCollection)
        {
            try
            {
                Outlook.NameSpace outlookNS = this.Application.GetNamespace("MAPI");
                Outlook.MAPIFolder mFolder = this.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                Outlook.MailItem mail = (Outlook.MailItem)outlookNS.GetItemFromID(entryIDCollection, Type.Missing);

                //mainForm.label1.Text = DateTime.Now.ToShortTimeString() + Environment.NewLine +
                //    "got mail from " + mail.Sender.Name + Environment.NewLine +
                //    "saying: " + mail.Body;

                if (mail.Subject.ToLower().Contains("mail2portfolio"))
                {
                    try
                    {
                        mainForm.Text = ">>" + mail.Body.Replace(' ', '+') + "<<";
                        var split = mail.Body.Split(new char[] { ' ' });
                        if (split.Length != 4)
                            throw new Exception("split.Length <> 4");
                        var trans = new Transaction
                        {   // example body:    AMD BUY 1000 2.55
                            Symbol = split[0],
                            Buy = split[1].ToLower() == "buy",
                            Time = DateTime.Today,
                            Amount = int.Parse(split[2]),
                            Price = decimal.Parse(split[3], CultureInfo.InvariantCulture),
                            Commission = 0,
                            Notes = "just testing",
                        };

                        mainForm.AddTrans_via_Queue(trans);
                        mainForm.Text = ">>trans added<<";
                    }
                    catch (Exception ex)
                    {
                        // ignore
                        mainForm.Text = ">>error: " + ex.Message + "<<";
                    }
                }
            }
            catch (Exception)
            {
                // ignore for the time being
            }
        }
    }
}
